const express = require("express")
const router = express.Router()
const bok = require("../../book")

router.get('/', (req, res) => {
    bok.findall((err, allbook) => {
        if (err) {
            throw err
        }
        res.render('index', { books: allbook })
    })

})

router.get('/add/book', (req, res) => {
    res.render('add')
})

router.post('/addBook', (req, res) => {
    let book = req.body
    bok.add(JSON.stringify(book), (err) => {
        if (err) {
            throw err
        }
        // 添加成功后，重定向到 /
        res.redirect('/')
    })
})

// 渲染更新页面
router.get('/update/book',(req,res)=>{
    let id = req.query.id
    stu.findById(Number(id),(err,book)=>{
        if(err){
            throw err
        }
        res.render('upbook',{book:book})
    })
})

router.post('/updateBook',(req,res)=>{
    let book = req.body
    bok.upbooks(JSON.stringify(book),(err)=>{
        if(err){
            throw err
        }
       res.redirect('/')
    })
})

router.get('/delete/book',(req,res)=>{
    let id = req.query.id
    bok.deleteById(Number(id),(err)=>{
        if(err){
            throw err
        }
       res.redirect('/')
    })
})
module.exports = router